<template>
  <div class="stats-panel">
    <div class="stats-panel-head stats-form">
      <h3>{{ $t('report.taskTeamChart.name') }}
        <el-popover trigger="hover">
          <div class="stats-popover-row">
            <div class="stats-popover-label">{{$t('report.taskTeamChart.state1')}}：</div>
            <div class="stats-popover-text">{{$t('report.taskTeamChart.text2')}}。</div>
          </div>
          <div class="stats-popover-row">
            <div class="stats-popover-label">{{$t('common.base.usualStatus.finish')}}：</div>
            <div class="stats-popover-text">{{$t('report.taskTeamChart.text1')}}。</div>
          </div>
          <stats-popover-icon slot="reference"></stats-popover-icon>
        </el-popover>
      </h3>
      <div class="stats-form-group">
        <!-- <div id="date-range" class="stats-form-daterange">
          <span>{{timeStart}} - {{timeEnd}}</span> 
          <b class="caret"></b>
        </div> -->
        <date-picker @datePicker="datePicker" />
      </div>
    </div>
    <div class="stats-panel-body"> 
      <div id="team-chart"></div>
      <stats-chart-empty v-if="empty">{{$t('common.base.tip.noData')}}</stats-chart-empty>

      <div class="stats-task-table-wrap" v-if="showTable">
        <div class="stats-task-table-header">
          <h3>{{$t('common.label.taskList')}}</h3>

          <button type="button" class="btn btn-primary btn-sm" @click="exportData" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.export') }}</button>
          <button type="button" class="btn btn-primary btn-sm" @click="exportAllData" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.exportAll') }}</button>
          <button type="button" class="btn btn-primary btn-sm" @click="showTable = false">{{ $t('common.base.collapse') }}</button>
        </div>
        <div class="stats-task-table">
          <el-table :data="page.list" class="stats-table">
            
            <el-table-column :label="$t('common.base.serialNumber')" prop="taskNo" width="150px" :show-overflow-tooltip="false">
              <template slot-scope="scope">
                <sample-tooltip :row="scope.row">
                  <template slot="content" slot-scope="{isContentTooltip}">
                    <el-tooltip :content="scope.row.taskNo" placement="top" :disabled="!isContentTooltip">
                      <a href="#" @click="openDetail(scope.row)">{{scope.row.taskNo}}</a>
                    </el-tooltip>
                  </template>
                </sample-tooltip>
              </template>
            </el-table-column>

            <el-table-column :label="$t('common.label.taskTemplate')" prop="templateName" width="120px"></el-table-column>
            <el-table-column :label="$t('common.base.customer')" prop="customer.name"></el-table-column>
            <el-table-column :label="$t('common.base.status')" prop="state" width="100px">
              <template slot-scope="scope">
                {{scope.row.state | taskStateName}}
              </template>
            </el-table-column>
            <!--
            <el-table-column label="团队" prop="templateName"></el-table-column>
            -->
           
            <el-table-column :label="$t('common.label.principalName')" width="120px">
              <template v-if="scope.row.executor" slot-scope="scope">
                <template v-if="isOpenData">
                  <open-data type="userName" :openid="scope.row.executor.staffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row.executor.displayName }}
                </template>
              </template>
            </el-table-column>

            <el-table-column :label="$t('common.base.createUser')" width="120px">
              <template v-if="scope.row.createUser" slot-scope="scope">
                <template v-if="isOpenData">
                  <open-data type="userName" :openid="scope.row.createUser.staffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row.createUser.displayName }}
                </template>
              </template>
            </el-table-column>
          
          </el-table>

          <el-pagination class="stats-pagination"
            background @current-change="jump"
            :current-page="page.pageNum"
            layout="total, prev, pager, next"
            :total="page.total">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform';
/*global AMap, moment, _init_data*/
import _ from "lodash";
import qs from 'src/util/querystring';

import http from 'src/util/HttpUtil';

import echarts from 'packages/Echarts';
import SampleTooltip from 'packages/SampleTooltip';
import { checkButtonDisplayed } from '@src/util/dom';
let chart = null;
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { t } from '@src/locales';
export default {
  name: 'task-team-chart',
  props: ['teamId', 'exportAuth', 'chartType', 'exportTrack'],
  data(){
    return {
      isOpenData,
      isButtonDisplayed: checkButtonDisplayed(),
      sort: '',
      timeStart: '',
      timeEnd: '',
      empty: false,

      showTable: false,
      model: {
        pageNum: 1,
        selectType: '',
        tagId: ''
      },
      page: {},
      exportNum: 0
    }
  },
  methods: {
    exportAllData(){
      if(this.exportNum > 1000 ) return this.$message({type: 'warning', message: t('report.common.exportNum',{num:1000})})
      let model = {
        tagId: this.model.tagId
      };

      if(this.timeStart) model.timeStart = this.timeStart;
      if(this.timeEnd) model.timeEnd = this.timeEnd;

      window.location.href = '/api/report/outside/stats/tagTask/exportAll?' + qs.stringify(model);

      this.exportTrack?.(true, false)
    },
    exportData(){
      if(this.exportNum > 1000 ) return this.$message({type: 'warning', message: t('report.common.exportNum',{num:1000})})
      let model = {
        tagId: this.model.tagId,
        selectType: this.model.selectType
      };

      if(this.timeStart) model.timeStart = this.timeStart;
      if(this.timeEnd) model.timeEnd = this.timeEnd;

      window.location.href = '/api/report/outside/stats/tagTask/export?' + qs.stringify(model);

      this.exportTrack?.(false, false)
    },
    openDetail(row){
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type:PageRoutesTypeEnum.PageTaskView,
        key:row.id,
        titleKey:row.taskNo,
        fromId
      })
      
    },
    jump(currentPage){
      this.model.pageNum = currentPage;
      this.renderTable();
    },
    chooseDate(start, end){
      this.$emit('trackEvent', 'chooseDate');

      this.timeStart = start;
      this.timeEnd = end;
      this.render();
    },
    async render(){
      try {

        let instance = this.$loading.show(this.$el);
        let data = await this.fetchData();
        instance.hide();
        //隐藏表格
        this.showTable = false;
      
        let option = this.getOption(data);
        if(null == option) {
          this.empty = true;
          return
        }
        chart.setOption(option);
      } catch (error) {
        console.log(error)
      }
    },
    fetchData(){
      let model = {
        timeStart: this.timeStart,
        timeEnd: this.timeEnd,
      }

      if(this.teamId){
        model.tagIds = this.teamId.split(',');
      }

      return http.post('/api/report/outside/stats/task/teamCount', model);
    },
    getOption(data = []){
      data = data.filter(item => {
        return item.unCompleteCount > 0 || item.CompleteCount > 0;
      })

      chart.clear();
      if(data.length == 0) return null;

      this.empty = false;

      let legend = [t('report.taskTeamChart.state1'), t('common.base.usualStatus.finish')];
      
      let xAxisData = [];
      let unFinishedData = [];
      let finishedData = [];

      let series = [];

      data.sort((prev, next) => {
        return next.unCompleteCount - prev.unCompleteCount
      }).forEach(item => {
        xAxisData.push(item.tagName);

        unFinishedData.push({
          name: t('report.taskTeamChart.state1'),
          value: item.unCompleteCount || 0,
          _origin: item
        });

        finishedData.push({
          name: t('common.base.usualStatus.finish'),
          value: item.CompleteCount || 0,
          _origin: item
        })
      })

      let dataZoomShow = false;
      let start = 0;
      let end = xAxisData.length - 1;
      if(xAxisData.length > 10){
        end = 9;
        dataZoomShow = true;
      }
      
      series.push({
        name: t('report.taskTeamChart.state1'),
        type: 'bar',
        barMaxWidth: 30,
        data: unFinishedData,
        barCategoryGap: '30px',
        itemStyle: { normal: {label : {show: true}}}
      })

      series.push({
        name: t('common.base.usualStatus.finish'),
        type: 'bar',
        barMaxWidth: 30,
        data: finishedData,
        barCategoryGap: '30px',
        itemStyle: { normal: {label : {show: true}}}
      })

      return {
        color: ["#2ec7c9","#ffb980"],
        tooltip : {
          trigger: 'axis',
          axisPointer : {           
            type : 'shadow'       
          }
        },
        toolbox: {
          feature: {
            saveAsImage: {
              name: t('report.taskTeamChart.name'),
            }
          },
          top: 10,
          right: 40
        },
        legend: {
          top: 10,
          left: 50,
          data: legend
        },
        dataZoom: [{
          type: 'slider',
          show: dataZoomShow,
          xAxisIndex: 0,
          startValue: start,
          endValue: end,
          bottom: '10px'
        }],
        grid: {
          top: 60,
          left: '50px',
          right: '40px',
          bottom: '60px',
          containLabel: true
        },
        xAxis : [
          {
            type: 'category',
            data: xAxisData,
            axisLabel: { 
              interval: 0, 
              rotate: 30, 
            }
          }
        ],
        yAxis : [
          {
            type : 'value'
          }
        ],
        series: series
      };
    },
    sortTAble (data = []) {
      data = data.filter(item => {
        return item.unCompleteCount > 0 || item.CompleteCount > 0;
      })
      if(data.length == 0) return null;

      let xAxisData = [];
      let unFinishedData = [];
      let finishedData = [];
      let series = [];
      
      if(this.sort == t('common.base.usualStatus.finish')) {
        data.sort((prev, next) => next.CompleteCount - prev.CompleteCount)
      } else {
        data.sort((prev, next) => next.unCompleteCount - prev.unCompleteCount);
      }
      data.forEach(item => {
        xAxisData.push(item.tagName);
        unFinishedData.push({
          name: t('report.taskTeamChart.state1'),
          value: item.unCompleteCount || 0,
          _origin: item
        });

        finishedData.push({
          name: t('common.base.usualStatus.finish'),
          value: item.CompleteCount || 0,
          _origin: item
        })
      });

      series.push({
        name: t('report.taskTeamChart.state1'),
        type: 'bar',
        barMaxWidth: 30,
        data: unFinishedData,
        barCategoryGap: '30px'
      })

      series.push({
        name: t('common.base.usualStatus.finish'),
        type: 'bar',
        barMaxWidth: 30,
        data: finishedData,
        barCategoryGap: '30px'
      })

      return {series,
              xAxisData
      }
    },
    init(start, end){
      this.timeStart = start;
      this.timeEnd = end;

      this.render();
    },
    initChart(){
      chart = echarts.init(document.getElementById("team-chart"));
      window.addEventListener('resize', _.debounce(function(){
        chart.resize();
      }))

      chart.on('click', event => {
        let origin = event.data._origin;
        this.exportNum = event.data.value
        let selectType = 'finish';

        if(event.seriesName == t('report.taskTeamChart.state1')) selectType = 'unFinish'
      
        this.model.pageNum = 1;
        this.model.tagId = origin.tagId;
        this.model.selectType = selectType;

        this.renderTable();
      })
      chart.on('legendselectchanged', async event => {
        let arr = [];
        for(let [key, value] of Object.entries(event.selected)) {
          arr.push({key, value});
        }
        arr.some(item => {
          if(item.value) {
            this.sort = item.key;
            return true;
          }
        })

        let data = await this.fetchData();
        let opt = chart.getOption(); 
        let sort = this.sortTAble(data);
        opt.series = sort.series;
        opt.xAxis[0].data = sort.xAxisData;
        chart.setOption(opt);
      })

      // this.render();
    },
    fetchTableData(){
      let model = {
        pageNum: this.model.pageNum,
        tagId: this.model.tagId,
        selectType: this.model.selectType,
        pageSize: 10
      };

      if(this.timeStart) model.timeStart = this.timeStart;
      if(this.timeEnd) model.timeEnd = this.timeEnd;

      return this.$http.post('/api/report/outside/stats/task/teamList', model);
    },
    async renderTable(){
      let instance = this.$loading.show(this.$el);
        
      this.fetchTableData().then(result => {
        this.page = result;
        this.showTable = true;
      })
      .catch(err => console.log(err))
      .finally(() => {
        instance.hide();
      })
    },
    datePicker(data) {
      // 初始化趋势图
      this.init(data[0], data[1]);
      this.chartType && this.$track.commonFn.chartTrack(this.chartType, 'REPORT_SEARCH_TIME', this.$track)
    }
  },
  mounted(){
    this.initChart();
  },
  watch: {
    teamId(){
      this.render();
    }
  },
  components: {
    [SampleTooltip.name]: SampleTooltip,
  }
}
</script>


<style lang="scss">
#team-chart{
  height: 520px;
}
</style>
